'use client';

import { useState, useEffect } from 'react';
import { Button, Card, Space, Tag, Typography, Spin, Alert, Divider, Row, Col, Statistic, Badge } from 'antd';
import Image from 'next/image';
import { 
  PlayCircleOutlined, 
  StopOutlined, 
  ExclamationCircleOutlined, 
  ReloadOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  FileTextOutlined,
  SettingOutlined,
  WifiOutlined
} from '@ant-design/icons';
import { handleApiResponse } from '@/utils/domUtils';
import styles from './page.module.scss';
import { useRouter } from 'next/navigation';

const { Title, Text } = Typography;

export default function SDModelPage() {
  const [status, setStatus] = useState<any>(null);
  const [logs, setLogs] = useState<string[]>([]);
  const [isConnected, setIsConnected] = useState(false);
  const [loading, setLoading] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [llmStatus, setLlmStatus] = useState<any>(null);
  const [llmConnected, setLlmConnected] = useState(false);
  const [sdStatus, setSdStatus] = useState<any>(null);
  const [sdConnected, setSdConnected] = useState(false);
  const [config, setConfig] = useState<any>(null);
  const router = useRouter();

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    fetch('/api/license/status').then(async (res) => {
      const result = await res.json();
      if (result.status !== 200) {
        router.push('/');
      }
    }).catch(() => {
      router.push('/');
    });
  }, []);

  const fetchConfig = async () => {
    try {
      const response = await fetch('/api/config');
      const result = await response.json();
      setConfig(result);
      return result;
    } catch (error) {
      console.error('获取配置失败:', error);
      return null;
    }
  };

  const apiCall = async (endpoint: string, method: string = 'GET') => {
    try {
      setLoading(true);
      const response = await fetch(`/api/sd${endpoint}`, { method });
      const result = await handleApiResponse(response);
      setLoading(false);
      return result;
    } catch (error) {
      setLoading(false);
      throw error;
    }
  };

  const startSDWebUI = async () => {
    try {
      await apiCall('/start', 'POST');
      updateStatus();
    } catch (error) {
      console.error('启动失败:', error);
    }
  };

  const stopSDWebUI = async () => {
    try {
      await apiCall('/stop', 'POST');
      updateStatus();
    } catch (error) {
      console.error('停止失败:', error);
    }
  };

  const forceStopSDWebUI = async () => {
    try {
      await apiCall('/stop?force=true', 'POST');
      updateStatus();
    } catch (error) {
      console.error('强制停止失败:', error);
    }
  };

  const updateStatus = async () => {
    try {
      const result = await apiCall('/status');
      console.log('状态API返回数据:', result);
      setStatus(result);
      setIsConnected(true);
    } catch (error) {
      console.error('状态更新失败:', error);
      setIsConnected(false);
    }
  };

  const updateLogs = async () => {
    try {
      const result = await apiCall('/logs');
      console.log('日志API返回数据:', result);
      setLogs(result.logs || []);
    } catch (error) {
      console.error('日志更新失败:', error);
    }
  };

  const updateLlmStatus = async () => {
    try {
      const response = await fetch('/api/ai-model/health');
      const result = await response.json();
      console.log('LLM状态API返回数据:', result);
      setLlmStatus(result);
      setLlmConnected(result.status === 'healthy');
    } catch (error) {
      console.error('LLM状态更新失败:', error);
      setLlmConnected(false);
      setLlmStatus(null);
    }
  };

  const updateSdStatus = async () => {
    try {
      // 动态获取配置中的SD WebUI基础URL
      let currentConfig = config;
      if (!currentConfig) {
        currentConfig = await fetchConfig();
      }
      
      if (!currentConfig || !currentConfig.sdWebUI) {
        console.error('SD配置获取失败:', currentConfig);
        throw new Error('无法获取SD WebUI配置');
      }
      
      const baseUrl = currentConfig.sdWebUI.baseUrl;
      console.log('尝试连接SD WebUI:', baseUrl);
      
      // 由于浏览器CORS限制，直接请求外部API可能失败
       // 应该通过后端代理来请求
       const response = await fetch('/api/sd/status?type=system-info');
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      console.log('SD状态API返回数据:', result);
      setSdStatus(result);
      setSdConnected(true);
    } catch (error) {
      console.error('SD状态更新失败:', error);
      console.error('错误详情:', error.message);
      setSdConnected(false);
      setSdStatus(null);
    }
  };

  const refreshStatus = async () => {
    // 确保配置是最新的
    await fetchConfig();
    await updateStatus();
    await updateLlmStatus();
    await updateSdStatus();
  };

  useEffect(() => {
    if (mounted) {
      // 先获取配置，然后进行状态更新
      const initializeApp = async () => {
        await fetchConfig();
        updateStatus();
        updateLogs();
        updateLlmStatus();
        updateSdStatus();
      };
      
      initializeApp();
    }
  }, [mounted]);

  return (
    <div className={styles.container}>
      {/* 顶部导航栏 */}
      <div className={styles.header}>
        <div className={styles.headerContent}>
          <div className={styles.headerLeft}>
            <div className={styles.logo}>
              <Image
                src="/logo.png"
                alt="Logo"
                width={32}
                height={32}
                priority
              />
            </div>
            <Title level={3} className={styles.title}>SD 模型服务启动器</Title>
          </div>
          <div className={styles.headerRight}>
            <Space>
              <Button
                icon={<SettingOutlined />}
                onClick={() => window.open('/admin/model-registration', '_blank')}
                type="text"
                title="模型注册管理"
              >
                模型注册
              </Button>
              <Badge 
                status={isConnected ? 'success' : 'error'} 
                text={isConnected ? '已连接' : '连接失败'} 
              />
              <Button
                icon={<ReloadOutlined />}
                onClick={refreshStatus}
                loading={loading}
                type="text"
                title="刷新状态"
              />
            </Space>
          </div>
        </div>
      </div>

      <div className={styles.content}>
        {/* 控制面板 */}
        <Card 
          title="控制面板" 
          className={styles.controlPanel}
          extra={
            <Text type="secondary">
              {sdConnected ? 'SD模型服务正常' : 'SD模型服务未连接'}
            </Text>
          }
        >
          <Space wrap>
            <Button
              type="primary"
              icon={<PlayCircleOutlined />}
              onClick={startSDWebUI}
              loading={loading}
              disabled={status?.isRunning}
              className={styles.startButton}
            >
              启动服务
            </Button>
            
            <Button
              danger
              icon={<StopOutlined />}
              onClick={stopSDWebUI}
              loading={loading}
              disabled={!status?.isRunning}
            >
              停止服务
            </Button>
            
            <Button
              icon={<ExclamationCircleOutlined />}
              onClick={forceStopSDWebUI}
              loading={loading}
              className={styles.forceStopButton}
            >
              强制停止
            </Button>
          </Space>
        </Card>

        {/* 服务状态与系统信息 */}
        <Row gutter={[16, 16]} className={styles.statusSection}>
          <Col xs={24}>
            <Card title="服务状态与系统信息" className={styles.statusCard}>
              <Row gutter={[24, 16]}>
                <Col xs={24} md={12}>
                  <Space direction="vertical" style={{ width: '100%' }}>

                    <div className={styles.statusItem}>
                      <Text>进程ID</Text>
                      <Text strong>{status?.pid || '--'}</Text>
                    </div>
                    
                    <div className={styles.statusItem}>
                      <Text>运行时间</Text>
                      <Text strong>
                        {status?.isRunning && status?.uptime 
                          ? `${Math.floor(status.uptime / 1000 / 60)}分钟`
                          : '--'
                        }
                      </Text>
                    </div>
                    
                    <div className={styles.statusItem}>
                      <Text>日志数量</Text>
                      <Text strong>{status?.logCount || 0}</Text>
                    </div>
                    
                    <div className={styles.statusItem}>
                      <Text>连接状态</Text>
                      <Tag 
                        color={isConnected ? 'success' : 'error'}
                        icon={<WifiOutlined />}
                      >
                        {isConnected ? '已连接' : '未连接'}
                      </Tag>
                    </div>
                  </Space>
                </Col>
                
                <Col xs={24} md={12}>
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <div className={styles.statusItem}>
                      <Text>SD WebUI路径</Text>
                      <Text strong className={styles.truncateText} title={status?.sdWebUIPath}>
                        {status?.sdWebUIPath ? status.sdWebUIPath.split('\\').pop() : '--'}
                      </Text>
                    </div>
                    
                    <div className={styles.statusItem}>
                      <Text>Python路径</Text>
                      <Text strong className={styles.truncateText} title={status?.pythonPath}>
                        {status?.pythonPath ? 'python.exe' : '--'}
                      </Text>
                    </div>
                    
                    <div className={styles.statusItem}>
                      <Text>启动脚本</Text>
                      <Text strong className={styles.truncateText} title={status?.launchScript}>
                        {status?.launchScript ? 'launch.py' : '--'}
                      </Text>
                    </div>
                  </Space>
                </Col>
              </Row>
            </Card>
          </Col>
          
          <Col xs={24} lg={12}>
            <Card title="SD模型服务状态" className={styles.statusCard}>
              <Space direction="vertical" style={{ width: '100%' }}>
                <div className={styles.statusItem}>
                  <Text>服务状态</Text>
                  <Tag 
                    color={sdConnected ? 'success' : 'error'}
                    icon={sdConnected ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
                  >
                    {sdConnected ? '服务正常' : '连接失败'}
                  </Tag>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>服务地址</Text>
                  <Text strong className={styles.truncateText} title={config?.sdWebUI?.baseUrl}>
                    {config?.sdWebUI?.baseUrl || '--'}
                  </Text>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>运行时间</Text>
                  <Text strong>
                    {sdStatus?.uptime || '--'}
                  </Text>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>当前步骤</Text>
                  <Text strong>
                    {sdStatus?.state?.step || '--'}
                  </Text>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>任务队列</Text>
                  <Text strong>
                    {sdStatus?.state?.jobs || '--'}
                  </Text>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>启动时间</Text>
                  <Text strong>
                    {sdStatus?.state?.started || '--'}
                  </Text>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>检测时间</Text>
                  <Text strong>
                    {sdStatus?.timestamp || '--'}
                  </Text>
                </div>
              </Space>
            </Card>
          </Col>
          
          <Col xs={24} lg={12}>
            <Card title="内存使用情况" className={styles.statusCard}>
              <Space direction="vertical" style={{ width: '100%' }}>
                {sdStatus?.memory?.ram && (
                  <>
                    <div className={styles.statusItem}>
                      <Text>系统内存</Text>
                      <Text strong>
                        {`${sdStatus.memory.ram.used.toFixed(2)}GB / ${sdStatus.memory.ram.total.toFixed(2)}GB`}
                      </Text>
                    </div>
                    <div className={styles.statusItem}>
                      <Text>内存使用率</Text>
                      <Text strong>
                        {`${((sdStatus.memory.ram.used / sdStatus.memory.ram.total) * 100).toFixed(1)}%`}
                      </Text>
                    </div>
                  </>
                )}
                
                {sdStatus?.memory?.gpu && (
                  <>
                    <div className={styles.statusItem}>
                      <Text>GPU显存</Text>
                      <Text strong>
                        {`${sdStatus.memory.gpu.used.toFixed(2)}GB / ${sdStatus.memory.gpu.total.toFixed(2)}GB`}
                      </Text>
                    </div>
                    <div className={styles.statusItem}>
                      <Text>显存使用率</Text>
                      <Text strong>
                        {`${((sdStatus.memory.gpu.used / sdStatus.memory.gpu.total) * 100).toFixed(1)}%`}
                      </Text>
                    </div>
                  </>
                )}
                
                {sdStatus?.memory?.['gpu-active'] && (
                  <>
                    <div className={styles.statusItem}>
                      <Text>GPU活跃内存</Text>
                      <Text strong>
                        {`当前: ${sdStatus.memory['gpu-active'].current.toFixed(2)}GB`}
                      </Text>
                    </div>
                    <div className={styles.statusItem}>
                      <Text>GPU峰值内存</Text>
                      <Text strong>
                        {`峰值: ${sdStatus.memory['gpu-active'].peak.toFixed(2)}GB`}
                      </Text>
                    </div>
                  </>
                )}
                
                {sdStatus?.memory?.utilization !== undefined && (
                  <div className={styles.statusItem}>
                    <Text>GPU利用率</Text>
                    <Text strong>
                      {`${sdStatus.memory.utilization}%`}
                    </Text>
                  </div>
                )}
                
                {sdStatus?.memory?.events && (
                  <>
                    <div className={styles.statusItem}>
                      <Text>重试次数</Text>
                      <Text strong>
                        {sdStatus.memory.events.retries || 0}
                      </Text>
                    </div>
                    <div className={styles.statusItem}>
                      <Text>内存溢出</Text>
                      <Text strong color={sdStatus.memory.events.oom > 0 ? 'error' : 'success'}>
                        {sdStatus.memory.events.oom || 0}
                      </Text>
                    </div>
                  </>
                )}
              </Space>
            </Card>
          </Col>
        </Row>

        {/* 模型服务状态 */}
        <Row gutter={[16, 16]} className={styles.statusSection}>
          <Col xs={24} lg={12}>
            <Card title="LLM模型服务状态" className={styles.statusCard}>
              <Space direction="vertical" style={{ width: '100%' }}>
                <div className={styles.statusItem}>
                  <Text>服务状态</Text>
                  <Tag 
                    color={llmConnected ? 'success' : 'error'}
                    icon={llmConnected ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
                  >
                    {llmStatus?.status === 'healthy' ? '服务正常' : 
                     llmStatus?.status === 'unhealthy' ? '服务异常' : 
                     llmStatus?.status === 'error' ? '连接失败' : '未知状态'}
                  </Tag>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>服务地址</Text>
                  <Text strong className={styles.truncateText} title={llmStatus?.service?.url}>
                    {llmStatus?.service?.url || '--'}
                  </Text>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>当前模型</Text>
                  <Text strong>
                    {llmStatus?.service?.model || '--'}
                  </Text>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>响应状态码</Text>
                  <Text strong>
                    {llmStatus?.service?.statusCode || '--'}
                  </Text>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>最大令牌数</Text>
                  <Text strong>
                    {llmStatus?.config?.maxTokens || '--'}
                  </Text>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>温度参数</Text>
                  <Text strong>
                    {llmStatus?.config?.temperature || '--'}
                  </Text>
                </div>
                
                <div className={styles.statusItem}>
                  <Text>检测时间</Text>
                  <Text strong>
                    {llmStatus?.timestamp ? new Date(llmStatus.timestamp).toLocaleString() : '--'}
                  </Text>
                </div>
                
                {llmStatus?.error && (
                  <div className={styles.statusItem}>
                    <Text>错误信息</Text>
                    <Text type="danger" className={styles.truncateText} title={llmStatus.error}>
                      {llmStatus.error}
                    </Text>
                  </div>
                )}
              </Space>
            </Card>
          </Col>
        </Row>

        {/* 实时日志 */}
        <Card 
          title="实时日志" 
          className={styles.logCard}
          extra={
            <Text type="secondary">
              最近 {logs.length} 条记录
            </Text>
          }
        >
          <div className={styles.logContainer}>
            {logs.length === 0 ? (
              <div className={styles.emptyLogs}>
                <FileTextOutlined />
                <Text type="secondary">暂无日志记录</Text>
              </div>
            ) : (
              <div className={styles.logList}>
                {logs.slice(-50).map((log, index) => (
                  <div key={index} className={styles.logItem}>
                    <span className={styles.logTime}>
                      {new Date().toLocaleTimeString()}
                    </span>
                    <span className={styles.logContent}>{log}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </Card>
      </div>

      {/* 加载遮罩 */}
      {loading && (
        <div className={styles.loadingOverlay}>
          <Card className={styles.loadingCard}>
            <Spin size="large" />
            <Text className={styles.loadingText}>处理中...</Text>
          </Card>
        </div>
      )}
    </div>
  );
}
